import './style/global.less';
import React, { useEffect } from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import { Message } from '@arco-design/web-react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import { queryUserInfo } from '@/services/user';
import { ModalServiceProvider } from '@/components/Modal';
import rootReducer from './store';
import PageLayout from './layout';
import Login from './pages/login/login';
import Register from './pages/login/register';
import Findpwd from './pages/login/findpwd';
import ServiceRule from './pages/rules/service';
import checkLogin from './utils/checkLogin';

import './mock';

const store = createStore(rootReducer);

function Index() {
  function fetchUserInfo() {
    store.dispatch({
      type: 'update-userInfo',
      payload: { userLoading: true },
    });
    queryUserInfo()
      .then((res) => {
        const { status, message, data } = res.data;
        if (status === 200) {
          store.dispatch({
            type: 'update-userInfo',
            payload: { userInfo: data, userLoading: false },
          });
        } else {
          Message.error(message || '服务器出错，请刷新重试');
        }
      })
      .catch(() => {
        store.dispatch({
          type: 'update-userInfo',
          payload: { userLoading: false },
        });
      });
  }

  // 判断为非用户信息操作路由
  function isUserOperateRoute() {
    const noNeedLoginRoute = ['register', 'login', 'findpwd', 'servicerule'];
    return noNeedLoginRoute.every(
      (item) => window.location.pathname.replace(/\//g, '') !== item
    );
  }

  useEffect(() => {
    if (checkLogin()) {
      if (isUserOperateRoute()) {
        // 获取用户信息
        fetchUserInfo();
      }
    } else {
      // 未登录状态
      if (isUserOperateRoute()) {
        window.location.pathname = '/login';
      }
    }
  }, []);

  return (
    <BrowserRouter>
      <Provider store={store}>
        <Switch>
          <Route path="/login" component={Login} />
          <Route path="/register" component={Register} />
          <Route path="/findpwd" component={Findpwd} />
          <Route path="/servicerule" component={ServiceRule} />
          <ModalServiceProvider>
            <Route path="/" component={PageLayout} />
          </ModalServiceProvider>
        </Switch>
      </Provider>
    </BrowserRouter>
  );
}

ReactDOM.render(<Index />, document.getElementById('root'));
